import React, {Component} from "react";
import {connect} from "dva";
import time, {currentTime, dateFormat} from "@/utils/time";
import echarts from "echarts";
import {addResizeHook} from "@/utils/resize";
import {Card, Col, Row, DatePicker} from "antd";
import moment from "moment";
import {trigger} from "@/utils/utils";


const {RangePicker} = DatePicker;

// 钒含量变化曲线
class LuzhaContentCurve extends Component {

  colors = ['#5793f3', '#d14a61'];

  state = {
    contentChange: null,
    // 默认定时任务trigger时间
    startTime: time.getStartOfDay(),
    endTime: time.getEndOfDay(),

    // 展示时间
    selectedStartTime: time.getStartOfDay(),
    selectedEndTime: time.getEndOfDay(),
    currentTime: null,
    data: [],
    chart: null,
    // defaultTimeSpan: 8,
    option: {
      color: this.colors,

      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        }
      },
      grid: {
        top: '8%',
        left: '8%',
        right: '8%',
        bottom: '14%'
      },
      legend: {
        data: ['实际值', '预测值']
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        splitLine: {
          show: false
        },
      },
      // xAxis: {
      //   type: 'time',
      //   splitLine: {
      //     show: false
      //   }
      // },
      yAxis: [
        {
          type: 'value',
          // name: '分数',
          position: 'left',
          // max: 100,
          // min: 0,
          splitNumber: 5,
          axisLine: {
            lineStyle: {
              color: this.colors[0]
            }
          },
          axisLabel: {
            formatter: '{value}'
          }
        }
      ],
      series: [
        {
          name: '实际值',
          type: 'line',
          // yAxisIndex: 0,
          data: []
        },
        {
          name: '预测值',
          type: 'line',
          // yAxisIndex: 1,
          data: []
        }
      ]
    },
    triggerTime: new Date()
  };

  stopLoop = false;
  reqRef = 0;

  randomId = 0;


  componentDidMount() {
    const {hasParent = false} = this.props;

    // 没有父页面驱动,需要自行获取数据
    if (!hasParent) {
      this.reqRef = requestAnimationFrame(() => {
        const {selectedStartTime,selectedEndTime} = this.state;
        trigger(
          ()=>this.getStatus(selectedStartTime,selectedEndTime),
          new Date().valueOf(),
          60 * 1000,
          true,
          () => this.stopLoop);
      });
    }

    // 基于准备好的dom，初始化echarts实例
    this.state.chart = echarts.init(document.getElementById("contentCurve"));
    // 绘制图表
    this.state.chart.setOption(this.state.option);
    addResizeHook(this, this.state.chart.resize)
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    const {contentChange, globalTime, hasParent} = nextProps;
    const {option, chart} = prevState;

    if (contentChange && prevState.chart !== null && contentChange !== prevState.contentChange && contentChange.date.length > 0) {
      option.series[0].data = contentChange.currentScore;
      option.series[1].data = contentChange.predictScore;
      option.xAxis.data = contentChange.date.map(str => str.replace(' ', '\n'));
      chart.setOption(option, true);

      if (globalTime && hasParent && prevState.currentTime !== globalTime.currentTime) {
        return {
          selectedStartTime: new Date(globalTime.currentTime.valueOf() - 24 * 60 * 60 * 1000),
          selectedEndTime: globalTime.currentTime,
          startTime: new Date(globalTime.currentTime.valueOf() - 24 * 60 * 60 * 1000),
          endTime: globalTime.currentTime,
          currentTime: globalTime.currentTime
        }
      }
    }
    return null
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    this.state.startTime = time.getStartOfDay();
    this.state.endTime = time.getEndOfDay();
  }

  componentWillUnmount() {
    cancelAnimationFrame(this.reqRef);
    this.stopLoop = true
  }

  timePick = (value) => {
    this.state.selectedStartTime = value[0].toDate();
    this.state.selectedEndTime = value[1].toDate();
    this.getStatus(
      this.state.selectedStartTime,
      this.state.selectedEndTime);
  };

  getStatus = (start,end) => {
    const payload = {
      start:dateFormat(start),
      end:dateFormat(end)
    };
    this.props.dispatch({
      type: 'hanfan/contentChange',
      payload
    });
  };

  reset = ()=> {
    const  {startTime,endTime} = this.state;
    this.setState({
      selectedStartTime:startTime,
      selectedEndTime: endTime
    })

    this.getStatus(
      startTime,
      endTime);
  };


  render() {
    const {
      width = 100,
      height = 300
    }
      = this.props;
    const {selectedStartTime, selectedEndTime} = this.state;
    const dateFormat = 'YYYY-MM-DD HH';
    return (
      <div>
        <RangePicker
          key={Math.random()} //强制刷新组件
          style={{width: 300}}
          showTime={{format: 'HH'}}
          format={dateFormat}
          placeholder={['开始时间', '结束时间']}
          onOk={this.timePick}
          defaultValue={[moment(selectedStartTime, dateFormat), moment(selectedEndTime, dateFormat)]}
        />

        <a style={{marginLeft: 5}} onClick={this.reset}>重置时间</a>

        <div id="contentCurve" style={{width: `${width}%`, height}}/>
      </div>

    )
  }
}

export default connect(({hanfan, global}) => ({
  contentChange: hanfan.contentChange,
  globalTime: hanfan.globalTime,
  global
}))
(LuzhaContentCurve);
